package com.d2.pay.rest;

import com.alibaba.fastjson.JSONObject;
import com.d2.pay.config.PayJSConfig;
import com.d2.pay.utils.payjs.HttpInvoker;
import com.d2.pay.utils.payjs.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class PayJsController {
    @Autowired
    private PayJSConfig payJSConfig;


    /**
     * 扫码支付
     * @param money
     * @return
     */
    @GetMapping(value = "pay/{money}/{body}")
    public String nativePay(@PathVariable("money") Integer money, @PathVariable("body") String body){
        Map<String,String> map = new HashMap<>();
        map.put("mchid", payJSConfig.getMchid());
        map.put("total_fee",""+money);
        String out_trade_no = "order"+System.currentTimeMillis();
        map.put("out_trade_no",out_trade_no);
        map.put("body",body);
        map.put("notify_url", "https://payjs.cn/help/");//请注意，，该路径需要payjs服务器可以直接访问，且结果为200。测试地址不行，www.baidu.com也不行
        String md5 = SignUtil.sign(map, payJSConfig.getKey());
        map.put("sign", md5.toUpperCase());
        map.put("body", map.get("body"));
        map.put("notify_url", map.get("notify_url"));
        String result = HttpInvoker.readContentFromPost("https://payjs.cn/api/native", map);
        JSONObject jsonObject = JSONObject.parseObject(result);

        return  jsonObject.getString("qrcode");
    }




    @ResponseBody
    @RequestMapping(value = "/notify/{outOrderNumber}")
    public Map<String,Object> payNotify(@PathVariable String outOrderNumber, String return_code, String total_fee,
                                        String out_trade_no, String payjs_order_id, String transaction_id, String time_end,
                                        String openid, String mchid, String sign){
        System.out.println("收到通知-----");
        System.out.println("outOrderNumber:"+outOrderNumber);
        System.out.println("return_code:"+return_code);
        System.out.println("total_fee:"+total_fee);
        System.out.println("out_trade_no:"+out_trade_no);
        System.out.println("payjs_order_id:"+payjs_order_id);
        System.out.println("transaction_id:"+transaction_id);
        System.out.println("time_end:"+time_end);
        System.out.println("openid:"+openid);
        System.out.println("mchid:"+mchid);
        System.out.println("sign:"+sign);
        return null;
    }
}
